package com.santiao.publics.util;

import android.util.Log;


import com.umeng.umcrash.UMCrash;
import com.santiao.publics.callback.OnResponseListener;
import com.santiao.publics.config.Const;
import com.santiao.fuel.SplashActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtilSS {
//    private static final String CONTENT_TYPE = "application/json;";
private static final String CONTENT_TYPE = "application/json; charset=utf-8";
public static  String XUpUA = "com.santiao.wifikeys/1.0.25"; // 应用包名/应用版本
private static final String TAG = "MainActivity";
private static final String KEY = "PKCS#8@6";



public static  void  adRequest(String actionType,String adStyle, String ecpm,String adId,String adPlatForm){
    if(adPlatForm==null || adPlatForm=="") {
        adPlatForm = "csj";
    }
  String   appId = SharedPreferencesUtil.getString("appId");
  String   djId  = SharedPreferencesUtil.getString("djId");
   Map<String,String>  map = new HashMap<>();

    map.put("djId",djId);//	djId		true

    map.put("appId",appId);//	APP唯一标识		true

    map.put("actionType",actionType);//	行为类型, 0:展示、1:点击	2加载广告	true

    map.put("adStyle",adStyle);//	广告样式, 0:信息流、1:全屏、2:插屏、3:激励视频、4:开屏、5:banner广告		true

    map.put("adPlatForm",adPlatForm);//	广告平台(可为空字符串、不能为空)、例：ks、oppo、csj(穿山甲)、bqt(百度)		true

    map.put("ecpm",ecpm);//	ecpm, 收益(单位:分)		true

    map.put("adId",adId);//	代码位ID		false

//        map.put("adChainId","");//	广告组链ID		false
//        map.put("appVersion","");//	APP当前版本		false
//
//        map.put("placementId","");//	广告位ID		false
//
//        map.put("scene","");//	应用内=iapp ; 应用外=oapp		false
//
//        map.put("sceneDetail","");//	场景详情, 0：无、1：锁屏、2：解锁、3：安装、4：卸载、5：打电话、6：切换网络、7：充电		false
    String url = Const.URL_Q+"/dj-tools-api/app/v2/report";
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
            HttpUtilSS.getRequest(url, map, new OnResponseListener() {
                @Override
                public void onSuccess(String response) {
                    Log.d(Const.TAG, url + "---ok-------:" + map.toString() + "----------:" + response);

                }

                @Override
                public void onError(String responseBody, String error) {
                    Log.d(Const.TAG, url + "---err-------:" + map.toString() + "----------:" +responseBody+"----------:"+ error);

                }
            });
//            }
//        });
}
 public static void getRequest(String url,Map<String, String> maps, OnResponseListener listener) {


    String XUpKey = UUID.randomUUID().toString(); // 随机32位字符 e6f2e949910c4df283b66254fe3e98bf
  //  XUpKey="55bd422c-245a-4406-91aa-b5151c93c3a3";

    long time = System.currentTimeMillis() ;
//        time=1715792692427L;
    maps.put("installDatetime", String.valueOf(time/ 1000));

    JSONObject jsonObject = new JSONObject(maps);
    String reqBody = jsonObject.toString();
 //   reqBody="{\"actionType\":\"0\",\"adId\":\"102603499\",\"ecpm\":\"0\",\"pkgName\":\"com.santiao.wifikeys\",\"appId\":\"a92c610a99219a18985e3a0843c83438e210b340\",\"adStyle\":\"2\",\"installDatetime\":\"1715873591\",\"androidId\":\"23423423424\",\"djId\":\"ee1a43b09791eb01\",\"adPlatForm\":\"csj\"}";
    // reqBody="{\"zz\":\"1715792692426\",\"pkgName\":\"com.santiao.wifikeys\",\"installDatetime\":\"1715792692\",\"key\":\"com.santiao.wifikeys\",\"androidId\":\"123456\",\"versionCode\":\"132\",\"oaids\":\"123456\"}";
     String responseBody = null;
    try {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse(CONTENT_TYPE);
        RequestBody body = RequestBody.create(mediaType,reqBody);
         String requestUrl = new URL(url).getPath();

        String headerStr = "X-Up-Key:" + XUpKey + "\n" + "X-Up-Timestamp:" + time;


      String type = "POST";
        String  md5 =  md5(reqBody.getBytes()).toUpperCase();
         String signature = genSignature(type,md5, CONTENT_TYPE, headerStr, requestUrl);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
//                    .addHeader("Content-Type", CONTENT_TYPE)
                .addHeader("X-Up-Timestamp", time+"")
                .addHeader("X-Up-UA", XUpUA)
                .addHeader("X-Up-Key", XUpKey)
//                    .addHeader("X-Up-Signature", genSignature("POST", DigestUtils.md5Hex(reqBody).toUpperCase(), CONTENT_TYPE, XUpKey, XUpTimestampAPI, url))
                .addHeader("X-Up-Signature", signature)
//                    .addHeader("X-Up-Signature", XUpKey)
                .build();
//            Log.d(Const.TAG, "post response-type: " + type);
//            Log.d(Const.TAG, "post response-reqBody: " + reqBody);
//            Log.d(Const.TAG, "post Content-Type: " + CONTENT_TYPE);
//            Log.d(Const.TAG, "post response-md5: " + md5);
//            Log.d(Const.TAG, "post response-XUpKey: " + XUpKey);
//            Log.d(Const.TAG, "post response-Timestamp: " + time);
//            Log.d(Const.TAG, "post response-XUpUA: " + XUpUA);
//            Log.d(Const.TAG, "post response-requestUrl: " + requestUrl);
//            Log.d(Const.TAG, "post response-signature: " + signature);
//



        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
              responseBody = response.body().string();
//                Log.d(Const.TAG, "post response-1: " + responseBody);
            if(responseBody.indexOf("code")==-1) {


                // 进行解密操作
                DES des = SecureUtil.des(KEY.getBytes());
                String result = des.decryptStr(responseBody);
//                System.out.println("post response: " + result);
//                    Log.d(Const.TAG, "post response-2: " + result);
                onSuccess(listener, result);
            }else{
                onSuccess(listener, responseBody);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        onError(listener,responseBody,e);
    }
}

public static String genSignature(String httpMethod, String contentMD5,
                                  String contentType , String headerStr, String relativePath) {
    try {
//            StringBuilder buf = new StringBuilder();
//            buf.append(httpMethod).append('\n')
//                    .append(contentMD5).append('\n')
//                    .append(contentType).append('\n')
//                    .append("X-Up-Key:").append(XUpKey).append('\n')
//                    .append("X-Up-Timestamp:").append(XUpTimestampAPI).append('\n')
//                    .append(reqUrl);
        StringBuffer buf = new StringBuffer();
        buf.append(httpMethod).append('\n').
                append(contentMD5).append('\n').
                append(contentType).append('\n').
                append(headerStr).append('\n').
                append("X-Up-UA:").append(XUpUA).append('\n').
                append(relativePath);

        String data = buf.toString();
        byte[] bytes = data.getBytes();
//            return DigestUtils.md5Hex(bytes);
        return md5(bytes);
//            return bytes.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}


    public static String md5(byte[]   input) {
        try {
            // 创建 MessageDigest 实例并指定算法为 MD5
            MessageDigest digest = MessageDigest.getInstance("MD5");

            // 使用指定的 byte 数组更新摘要
            byte[] bytes = digest.digest(input);

            // 将 byte 数组转换为十六进制字符串
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : bytes) {
                stringBuilder.append(String.format("%02x", b));
            }

            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    private static void onError(OnResponseListener listener,String responseBody, Exception onError) {
        if(listener!=null) {
            listener.onError(responseBody,onError.toString());
        }
    }

    private static void onSuccess(  OnResponseListener listener,String responseBody) throws IOException {

    if(listener!=null) {
        listener.onSuccess(responseBody);
    }

    }



    public static  boolean updateConfigAdSet(String url,String response,String mymanufacturer,Map<String, String> map){
        LogUtil.d(Const.TAG, url + "---ok-------:" + map.toString() + "----------:" + response);

        boolean ifban= false;
        try {
            boolean ifintiAd = false;
            boolean ifintiAd2= false;

            JSONObject jsonObject = new JSONObject(response);


            if (jsonObject.getInt("code") == 200) {
                if (jsonObject.has("data")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    int ban_status  = data.getInt("ban_status");//1封禁 0正常
                    int check_flag  = data.getInt("check_flag");// 审核模式1 审核 0 非审核
                    int ad_switch  = data.getInt("ad_switch");//1显示广告
//                                            ad_switch =1;
                    int curr_channel  = 0;//0 自然量 >0为归因用户
                    if(data.has("curr_channel")){
                        curr_channel = data.getInt("curr_channel");
                    }
                    SplashActivity.userNo = data.getString("riseId");



                    if (   ban_status!= 1) { //
                        if(ad_switch == 1
                                || ("huawei".equals(mymanufacturer) && check_flag==0)//华为非审核模式全部归因
                        ){
//                                              if(true){
                            ifintiAd = true;
                        }else if ( curr_channel==0 && check_flag==0 ) {// 自然量关闭审核模式
//                                              }else if ( true ) {// 关闭审核模式，与归因都显示广告

                            // 广告2模式
                            ifintiAd2 = true;

                        }

//                                              if(ifintiAd ||  ifintiAd2) { //  用户检查是否包含 com.vivo.autotest.screen_record  包 关闭所有广告
//                                                  if ("vivo".equals(mymanufacturer)) {
//                                                      if (ApplicationUtil.ifPackageName(mContext, "com.vivo.autotest.screen_record")) {
//                                                          ifintiAd2= false;
//                                                          ifintiAd = false;
//                                                      }
//                                                  }
//
//                                              }


                    }else{
                        ifban = true;//封禁
                    }




                    String appId = data.getString("app_id");
                    String djId = data.getString("djId");
                    if (appId == null || appId.isEmpty()) {

                    } else {
                        SharedPreferencesUtil.saveString("appId", appId);

                    }
                    if (djId == null || djId.isEmpty()) {

                    } else {
                        SharedPreferencesUtil.saveString("djId", djId);

                    }

                }
            }


            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, ifintiAd);
            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD_2, ifintiAd2);
            ////

        } catch (Exception e) {
            if (Const.IF_UM) {
                UMCrash.generateCustomLog(e, "installJson");
            }
            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);
            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD_2, false);
        }finally {
            return  ifban;
        }
    }


    //config获取数据
    public static void getRequestConfig(String url, Map<String, String> maps, OnResponseListener listener) {

        String XUpKey = UUID.randomUUID().toString(); // 随机32位字符 e6f2e949910c4df283b66254fe3e98bf
        //  XUpKey="55bd422c-245a-4406-91aa-b5151c93c3a3";

        long time = System.currentTimeMillis() ;
//        time=1715792692427L;
//        maps.put("installDatetime", String.valueOf(time/ 1000));

        JSONObject jsonObject = new JSONObject(maps);
        String reqBody = jsonObject.toString();
        //   reqBody="{\"actionType\":\"0\",\"adId\":\"102603499\",\"ecpm\":\"0\",\"pkgName\":\"com.santiao.wifikeys\",\"appId\":\"a92c610a99219a18985e3a0843c83438e210b340\",\"adStyle\":\"2\",\"installDatetime\":\"1715873591\",\"androidId\":\"23423423424\",\"djId\":\"ee1a43b09791eb01\",\"adPlatForm\":\"csj\"}";
        // reqBody="{\"zz\":\"1715792692426\",\"pkgName\":\"com.santiao.wifikeys\",\"installDatetime\":\"1715792692\",\"key\":\"com.santiao.wifikeys\",\"androidId\":\"123456\",\"versionCode\":\"132\",\"oaids\":\"123456\"}";
        String responseBody = null;
        try {
            OkHttpClient client = new OkHttpClient();

            MediaType mediaType = MediaType.parse(CONTENT_TYPE);
            RequestBody body = RequestBody.create(mediaType,reqBody);
            String requestUrl = new URL(url).getPath();

            String headerStr = "X-Up-Key:" + XUpKey + "\n" + "X-Up-Timestamp:" + time;

            StringBuilder urlBuilder = new StringBuilder(url);
            if (maps != null && !maps.isEmpty()) {
                urlBuilder.append("?");
                for (Map.Entry<String, String> entry : maps.entrySet()) {
                    urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                // 移除最后一个 &
                urlBuilder.deleteCharAt(urlBuilder.length() - 1);
            }

            url = urlBuilder.toString();

            String type = "GET";
            String  md5 =  md5(reqBody.getBytes()).toUpperCase();
            String signature = genSignature(type,  CONTENT_TYPE, headerStr, requestUrl);
            Request request = new Request.Builder()
                    .url(url)
                    .get()
//                    .addHeader("Content-Type", CONTENT_TYPE)
                    .addHeader("X-Up-Timestamp", time+"")
                    .addHeader("X-Up-UA", XUpUA)
                    .addHeader("X-Up-Key", XUpKey)
//                    .addHeader("X-Up-Signature", genSignature("POST", DigestUtils.md5Hex(reqBody).toUpperCase(), CONTENT_TYPE, XUpKey, XUpTimestampAPI, url))
                    .addHeader("X-Up-Signature", signature)
//                    .addHeader("X-Up-Signature", XUpKey)
                    .build();
//            Log.d(Const.TAG, "post response-type: " + type);
//            Log.d(Const.TAG, "post response-reqBody: " + reqBody);
//            Log.d(Const.TAG, "post Content-Type: " + CONTENT_TYPE);
//            Log.d(Const.TAG, "post response-md5: " + md5);
//            Log.d(Const.TAG, "post response-XUpKey: " + XUpKey);
//            Log.d(Const.TAG, "post response-Timestamp: " + time);
//            Log.d(Const.TAG, "post response-XUpUA: " + XUpUA);
//            Log.d(Const.TAG, "post response-requestUrl: " + requestUrl);
//            Log.d(Const.TAG, "post response-signature: " + signature);
//



            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                responseBody = response.body().string();
//                Log.d(Const.TAG, "post response-1: " + responseBody);
                if(responseBody.indexOf("code")==-1) {


                    // 进行解密操作
                    DES des = SecureUtil.des(KEY.getBytes());
                    String result = des.decryptStr(responseBody);
//                System.out.println("post response: " + result);
//                    Log.d(Const.TAG, "post response-2: " + result);
                    onSuccess(listener, result);
                }else{
                    onSuccess(listener, responseBody);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            onError(listener,responseBody,e);
        }
    }


    public static String genSignature(String httpMethod,
                                      String contentType , String headerStr, String relativePath) {
        try {
//            StringBuilder buf = new StringBuilder();
//            buf.append(httpMethod).append('\n')
//                    .append(contentMD5).append('\n')
//                    .append(contentType).append('\n')
//                    .append("X-Up-Key:").append(XUpKey).append('\n')
//                    .append("X-Up-Timestamp:").append(XUpTimestampAPI).append('\n')
//                    .append(reqUrl);
            StringBuffer buf = new StringBuffer();
            buf.append(httpMethod).append('\n').
//                    append(contentMD5).append('\n').
//                    append(contentType).append('\n').
        append(headerStr).append('\n').
                    append("X-Up-UA:").append(XUpUA).append('\n').
                    append(relativePath);

            String data = buf.toString();
            byte[] bytes = data.getBytes();
//            return DigestUtils.md5Hex(bytes);
            return md5(bytes);
//            return bytes.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }


    }
}
